package cn.icatw.leetcode.editor.cn;
//给定两个整数数组 preorder 和 inorder ，其中 preorder 是二叉树的先序遍历， inorder 是同一棵树的中序遍历，请构造二叉树并
//返回其根节点。
//
//
//
// 示例 1:
//
//
//输入: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
//输出: [3,9,20,null,null,15,7]
//
//
// 示例 2:
//
//
//输入: preorder = [-1], inorder = [-1]
//输出: [-1]
//
//
//
//
// 提示:
//
//
// 1 <= preorder.length <= 3000
// inorder.length == preorder.length
// -3000 <= preorder[i], inorder[i] <= 3000
// preorder 和 inorder 均 无重复 元素
// inorder 均出现在 preorder
// preorder 保证 为二叉树的前序遍历序列
// inorder 保证 为二叉树的中序遍历序列
//
//
// Related Topics 树 数组 哈希表 分治 二叉树 👍 2325 👎 0


import java.util.HashMap;

//Java：从前序与中序遍历序列构造二叉树
public class T105_ConstructBinaryTreeFromPreorderAndInorderTraversal {
    public static void main(String[] args) {
        Solution solution = new T105_ConstructBinaryTreeFromPreorderAndInorderTraversal().new Solution();
        // TO TEST
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     * int val;
     * TreeNode left;
     * TreeNode right;
     * TreeNode() {}
     * TreeNode(int val) { this.val = val; }
     * TreeNode(int val, TreeNode left, TreeNode right) {
     * this.val = val;
     * this.left = left;
     * this.right = right;
     * }
     * }
     */
    class Solution {
        //前序遍历
        private int[] preorder;
        //中序遍历
        private int[] inorder;
        private HashMap<Integer, Integer> inorderIndexMap;
        private int preIndex = 0;

        public TreeNode buildTree(int[] preorder, int[] inorder) {
            this.inorder = inorder;
            this.preorder = preorder;
            this.inorderIndexMap = new HashMap<>();
            //    将中序遍历的值和索引存入map
            for (int i = 0; i < inorder.length; i++) {
                inorderIndexMap.put(inorder[i], i);
            }
            return buildTree(0, inorder.length - 1);
        }

        private TreeNode buildTree(int left, int right) {
            if (left > right) {
                return null;
            }
            //选择前序遍历的第一个节点作为根节点
            int rootVal = preorder[preIndex++];
            TreeNode root = new TreeNode(rootVal);
            //根据中序遍历的根节点的索引划分左右子树
            int inorderIndex = inorderIndexMap.get(rootVal);
            //构造左右子树
            root.left = buildTree(left, inorderIndex - 1);
            root.right = buildTree(inorderIndex + 1, right);
            return root;
        }
    }

    //leetcode submit region end(Prohibit modification and deletion)
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
